﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SMTPAPI.Interfaces;
using System.Net.Mail;
using SMTPAPI.Enums;

namespace SMTPAPI.InterfaceImplementation
{
    public class Mail:IMail
    {
        public bool SendMail(SmtpClient smtpClient, MailMessage mailMessage, IList<RecieversList> recieverList)
        {
            try
            {
                if (recieverList != null)
                {
                    AddRecieverList(recieverList, mailMessage);
                    smtpClient.Send(mailMessage);
                }

                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void AddRecieverList(IList<RecieversList> recieverList, MailMessage mailMessage)
        {
            foreach (RecieversList rlist in recieverList)
            {
                switch (rlist.RecieverType)
                {
                    case RecieverTypes.TO:
                        {
                            mailMessage.To.Add(GenerateRecieverList(rlist.RecieverList));
                            break;
                        }
                    case RecieverTypes.Cc:
                        {
                            mailMessage.CC.Add(GenerateRecieverList(rlist.RecieverList));
                            break;
                        }
                    case RecieverTypes.Bcc:
                        {
                            mailMessage.Bcc.Add(GenerateRecieverList(rlist.RecieverList));
                            break;
                        }
                    default:
                        {
                            break;
                        }
                }
            }
        }

        private string GenerateRecieverList(IList<string> recieverList)
        {
            string recievers = string.Empty;

            if (recieverList != null)
            {
                foreach (string reciever in recieverList)
                {
                    if (recievers == string.Empty)
                    {
                        recievers = reciever;
                    }
                    else
                    {
                        recievers = recievers + "," + reciever;
                    }
                }
            }
            return recievers;
        }
    }
}
